package me.seu.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.javafaker.Faker;
import lombok.extern.slf4j.Slf4j;
import me.seu.demo.entity.Item;
import me.seu.demo.repository.ItemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * 往ES中增删改查数据
 *
 * @author liangfeihu
 * @since 2020/4/22 18:44
 */
@Slf4j
@RestController
@RequestMapping("/es")
public class EsCrudController {

    private final Faker faker = new Faker(Locale.CHINA);

    @Autowired
    ItemRepository itemRepository;

    @GetMapping("/insert/item")
    public ResponseEntity insertEsData() {

        Item item = new Item(1L, "小米手机7", "手机",
                "小米", 3499.00, "http://image.baidu.com/13123.jpg");
        Item returnItem = itemRepository.save(item);
        log.info("[itemRepository.save(item)] return={}", JSONObject.toJSONString(returnItem));

        return ResponseEntity.ok("insert elasticsearch item data success");
    }

    @GetMapping("/insert/item/batch")
    public ResponseEntity insertEsDataList() {
        List<Item> list = new ArrayList<>();
        list.add(new Item(2L, "坚果手机R1", "手机", "锤子", 3699.00, "http://image.baidu.com/13123.jpg"));
        list.add(new Item(3L, "华为META10", "手机", "华为", 4499.00, "http://image.baidu.com/13123.jpg"));

        list.add(new Item(4L, "华为Mate20Pro", "手机", "华为", 5199.00, "http://image.baidu.com/13123.jpg"));

        // 接收对象集合，实现批量新增
        itemRepository.saveAll(list);

        return ResponseEntity.ok("insert elasticsearch item batch data success");
    }

    @GetMapping("/delete/item")
    public ResponseEntity deleteEsData(@RequestParam("id") Long id) {

        itemRepository.deleteById(id);

        return ResponseEntity.ok("delete elasticsearch item data success");
    }

    @GetMapping("/faker/data")
    public ResponseEntity getFakerData() {
        String job = faker.job().title();
        log.info("faker job info = {}", job);
        String address = faker.address().fullAddress();
        log.info("faker address = {}", address);
        return ResponseEntity.ok("get faker data success");
    }

}
